package com.common.utils.timeUtils
{
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	/**
	 * 时间管理器 
	 * @author Administrator
	 * 
	 */	
	public class TimerManager
	{
		private var _timer:Timer;
		/**
		 *保存返回函数 
		 */
//		private var _funObj:Object;
		private var _funDic			:Dictionary;
		private static var _instance	:TimerManager;
		private var _tempTime			:int;	//保存临时时间
		private var _passTime			:int;	//当前时间－过去的当前时间  ＝ 过去的时间
		private var _surplusTime		:int;//剩余时间 ＝ _tempTime - 1000
		
		public function TimerManager()
		{
			init();
		}
		/**
		 *初始化 
		 * 
		 */		
		private function init():void
		{
			_funDic = new Dictionary();
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER,onTimerHandler);
			_tempTime = getTimer();
			_timer.start();
		}
		/**
		 * 时间间隔触发
		 * @param event
		 * 
		 */		
		protected function onTimerHandler(event:TimerEvent):void
		{
			_passTime = getTimer() - _tempTime +_passTime;
			_tempTime = getTimer();
			carryoutFunction();
		}
		/**
		 *执行回调函数 
		 * 
		 */
		private function carryoutFunction():void
		{
			_surplusTime = _passTime - 1000;
			if(_surplusTime < 0)return;
			_passTime = _surplusTime;
			for each(var callBack:Function in _funDic)
			{
				callBack.apply();
			}
			if(_surplusTime > 1000)
			{
				carryoutFunction();
			}
		}
		/**
		 *增加回调函数 
		 * @param $callBack
		 * 
		 */
		public function addFunction($callBack:Function):void
		{
			_funDic[$callBack] = $callBack;
		}
		/**
		 *删除回调函数 
		 * @param $callBack
		 */
		public function removeFunction($callBack:Function):void
		{
			if($callBack != null)
				delete _funDic[$callBack];
		}
		/**
		 *获取实例 
		 * @return 
		 * 
		 */		
		public static function get instance():TimerManager
		{
			if(_instance == null)_instance = new TimerManager();
			return _instance;
		}
	}
}